
import { defineComponent, reactive, onMounted, watchEffect, VueElement, onUnmounted } from "vue";
import Skeleton from '@/components/Skeleton';
import Card from '@/components/Card';
import Map from './Map';
import {
  cflrsgzFn,
  fhsjcpslFn,
  bbzxFn,
  barSzhcgslFn,
  lineSzhcgslFn,
  initAbnormalEventLocationRelationshipData, sjlxblsxFn, initEChartSjyxjfb
} from "./chart";

import './style.less';
import {energyProportion} from "@/views/VillageLevel/chart";
import axios from "axios";

interface AbnormalItem {
  [key: string]: string
}

interface State {
  title?: string,
  mapType?: string,
  isInfoBox?: boolean,
  shuzihua: any[],
  huodongNumber: any[],
  activeRpa: 'in' | 'out',
  activeForm: 'dev' | 'gen',
  fhsjcpsl: echarts.ECharts | null,
  bbzx: echarts.ECharts | null,
  journalCount: number,
  scrollInterval: number,
  xTableData:{
    dtos: any[],
    name: string,
    names: any[],
    type: any,
    values: any[],
  },
  mbfwzjbList: any[],
  styxjfbList: any[],
  tableData: any[],
  achievementAggregationTimer: any
}

export default defineComponent(() => {

  const state = reactive<State>({
    title: '智护视界日志数据可视化',
    mapType: 'bg2',
    isInfoBox: true,
    activeRpa: 'in',
    activeForm: 'dev',
    fhsjcpsl: null,
    bbzx: null,
    shuzihua: [
      { "color": "#218FF7", "name": "推广任务数", "value": 19, "icon": "icon-1.png" },
      { "color": "#00FF96", "name": "上报成果", "value": 11, "icon": "icon-2.png" },
      { "color": "#FFE16A", "name": "承担项目", "value": 8, "icon": "icon-3.png" },
    ],
    huodongNumber: [
      { "color": "#218FF7", "name": "活动总数", "value": 5, "icon": ["icon-5.png", "blue.png"] },
      { "color": "#00FF96", "name": "竞赛类", "value": 3, "icon": ["icon-6.png", "green.png"] },
      { "color": "#218FF7", "name": "创新类", "value": 2, "icon": ["icon-7.png", "blue.png"] },
    ],
    journalCount: 0,
    xTableData:{
      dtos: [],
      name: "",
      names: [],
      type: null,
      values: [],
    },
    scrollInterval: 0,
    mbfwzjbList: [],
    styxjfbList: [],
    tableData: [],
    achievementAggregationTimer: null
  });

  const getImageUrl = (name: string) => {
    return new URL(`../../assets/achievement-aggregation/${name}`, import.meta.url).href
  }
  /**
   * 监听某个状态的改变
   */
  watchEffect((onInvalidate)=>{
    /**
     * 当组件失效，watchEffect被主动停止或者副作用即将重新执行时，这个函数会执行
     */
    onInvalidate(()=>{})
  },{
    /**
     * post: 在组件更新后触发，这样你就可以访问更新的 DOM。
     * pre: 默认值，在组件更新前触发
     * sync: 同步触发，低效
     */
    flush: 'post'
  });

  /**
   * Rpatab切换
   * @param value table的name
   */
   const handleChangeRpa = (value: State['activeRpa']) => {
    state.activeRpa = value;
    const values = {
      in: [
        { value: 310 },
        { value: 60 },
        { value: 30 },
        { value: 30 },
      ],
      out: [
        { value: 200 },
        { value: 90 },
        { value: 10 },
        { value: 10 },
      ]
    }
    state.fhsjcpsl?.setOption({
      series: [
        {},
        { data: values[value] },
        {},
        {},
      ]
    })
  }
  const handleChangeForm = (value: State['activeForm']) => {
    state.activeForm = value;
    const values = {
      dev: [4, 26, 2, 1, 8],
      gen: [29582, 34562, 12562, 5995, 18584]
    }
    state.bbzx?.setOption({
      series: [
        {
          data: values[value]
        },
        {
          data: values[value].map(() => 1)
        },
        {
          data: values[value]
        }
      ]
    })
  }

  const getTableData = async () => {
    const res = await axios.post("http://localhost:8080/x_TableData");
    const data = res.data.data;
    state.xTableData = data;
    state.journalCount = data.count2;
    state.tableData = data.l2;
  }

  const getMbfwzjbFn = async () => {
    state.mbfwzjbList = []
    const res = await axios.post("http://localhost:8080/x9");
    const data = res.data.data;
    let num:number = 0;
    data.values.forEach((item:any)=>{
      num += item;
    })
    data.dtos.forEach((item:any,index:number)=>{
      const temp = (item.value / num * 100).toFixed(2);
      state.mbfwzjbList.push(
          {"title": `${item.name}日志`, "value": temp, "realValue": item.value, "name":item.name, "color": index ? '#3699F4' : '#57DA8C'},
      )
    })
  }

  const getStyxjfbData = async () => {
    const res = await axios.post("http://localhost:8080/x7");
    const data = res.data.data;
    let max: number = Math.max(...data.values);
    max = Math.floor((max * 1.2));
    data.dtos.forEach((item:any)=>{
      state.styxjfbList.push({
        "label":item.name, "value":item.value, "max":max
      })
    })
  }

  const initData = () => {
    initAbnormalEventLocationRelationshipData();
    getStyxjfbData();
    getMbfwzjbFn();
    cflrsgzFn();
    lineSzhcgslFn();
    sjlxblsxFn();
    initEChartSjyxjfb();
  }

  onUnmounted(() => {
    clearInterval(state.achievementAggregationTimer)
  })

  onMounted(() => {
    getTableData();
    initAbnormalEventLocationRelationshipData();
    getStyxjfbData();
    getMbfwzjbFn();
    cflrsgzFn();
    lineSzhcgslFn();
    sjlxblsxFn();
    initEChartSjyxjfb();
    state.achievementAggregationTimer = setInterval(()=>{
      initData();
    },10000)
    // barSzhcgslFn();
    // state.bbzx = bbzxFn();
    // state.fhsjcpsl = fhsjcpslFn();
    // industrialValueAdded();
    // energyPerUnitOutput();
    // energyTop10();

    /**
     * 表格自动滚动
     */
    const tbody = document.querySelector(".scrollable-tbody") as HTMLElement;

    function startAutoScroll() {
      state.scrollInterval = setInterval(() => {
        tbody.scrollTop += 1; // 修改这个值以调整滚动速度
        /**
         * 滚动到末尾自动回到顶部
         */
        if (tbody.scrollTop >= tbody.scrollHeight - tbody.clientHeight) {
          tbody.scrollTop = 0;
        }
      }, 20); // 修改这个值以调整滚动频率
    }

    function stopAutoScroll() {
      clearInterval(state.scrollInterval);
    }

    // 鼠标移入暂停滚动
    tbody.addEventListener("mouseenter", stopAutoScroll);

    // 鼠标移出恢复滚动
    tbody.addEventListener("mouseleave", startAutoScroll);

    // 页面加载完毕开始自动滚动
    startAutoScroll();
  });

  return () => {
    const { title, mapType, mbfwzjbList } = state;

    return (
      <Skeleton title={title} mapType={mapType}>
        <div class="achievement-aggregation">
          <div class="aa-left">
            <Card
              title="当前日志数量" style="margin-top: 30px;height: 20%" class="abnormal-data-key"
            >
              <div class="shuzihualianluoren">
                <div class="aa-img">
                  <img class="aa-img3" src={getImageUrl('base.png')} />
                  <img class="aa-img2" src={getImageUrl('light efficiency-1.png')} />
                  <img class="aa-img1" src={getImageUrl('icon-4.png')} />
                </div>
                <div class="aa-value">
                  <div class="aav-item">
                    <span class="aavi-title">日志</span>
                    <span class="aavi-value">{state.journalCount}</span>
                  </div>
                </div>
              </div>
            </Card>
            <Card title="异常日志事件比" style="margin-top: 30px">
              <div class="energy-proportion">
                {
                  state.mbfwzjbList.map((item, index) => {
                    return (
                        <div class="ep-item">
                          <div
                              class={`ep-item_${index}`}
                              style="width: 100%; height: 100%"
                          >
                            {
                              setTimeout(() => {
                                energyProportion(`.ep-item_${index}`, item.value, item.color)
                              }, 0)
                            }
                          </div>
                          <span class="epi-proportion">
                          {item.value}%
                        </span>
                          <span class="epi-title">{item.title}</span>
                        </div>
                    )
                  })
                }
              </div>
              <div class="left-szhnlkapt-title">数据情况</div>
              <div class="chart_item" style="flex-direction: column;">
                <div class="tips">
                    <div class="tips_item">
                      <span class="label">{mbfwzjbList[0]?.name}</span>
                      <span class="value">{mbfwzjbList[0]?.realValue}</span>
                      <span class="unit">次</span>
                    </div>
                    <div class="tips_item">
                    <span class="label">{mbfwzjbList[1]?.name}</span>
                    <span class="value" style="color: rgba(60, 255, 223, 1)">
                      {mbfwzjbList[1]?.realValue}
                    </span>
                    <span class="unit">次</span>
                    </div>

                </div>
              </div>
            </Card>
            <Card title="异常日志关系" style="margin-top: 10px;height: 20%">
              <div
                class="chart-ycsjwzgx"
                style="width: 100%;height: 100%"
              />
            </Card>
            <Card
              title="异常事件次数分布"
              style="margin-top: 10px;height: 20%"
            >
              <div class="chart-sjyxjfb"
                   style="width: 100%;height: 100%"></div>
              <div style={{
                padding: '28px 16px 0 16px',
                fontFamily:'Arial, sans-serif',
                display: 'none'
              }}>
                {[
                  { label: state.styxjfbList[0]?.label, value:state.styxjfbList[0]?.value, max :state.styxjfbList[0]?.max, color :'#38DDFB', fontColor: 'linear-gradient(0deg, #EDB058 0%, rgba(255,255,255,0.55) 100%)'},
                  { label: state.styxjfbList[1]?.label, value:state.styxjfbList[1]?.value, max :state.styxjfbList[1]?.max, color :'#38DDFB', fontColor: 'linear-gradient(-33deg, rgb(165 165 165 / 83%) 0%, rgba(255, 255, 255, 0.83) 23.0225%, rgb(177 177 177 / 83%) 41.4062%, rgba(255, 255, 255, 0.83) 67.0654%, rgb(203 203 203 / 83%) 82.9346%, rgba(255, 255, 255, 0.83) 100%) text'},
                  { label: state.styxjfbList[2]?.label, value:state.styxjfbList[2]?.value, max :state.styxjfbList[2]?.max, color :'#38DDFB', fontColor: 'linear-gradient(0deg, #DC9F75 0%, rgba(255,255,255,0.55) 100%)'},
                ].map(({ label, value, max, color, fontColor }, i) =>
                  (
                    <div key={i} style={{ marginBottom: '30px', marginLeft: '100px', position: 'relative' }}>
                      <div style={{
                        position: 'absolute',
                        top: '17px',
                        left: '-110px',
                        'font-family': 'biaoti',
                        'font-size': '32px',
                        background: fontColor,
                        '-webkit-background-clip': 'text',
                        '-webkit-text-fill-color': 'transparent'
                      }}>TOP{i + 1}</div>
                      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '5px' }}>
                        <span style={{ color: '#fff', fontSize: '28px', marginBottom: '5px' }}>{label}</span>
                        <span style={{
                          color: '#0084FF',
                          fontSize: '36px',
                          transform: 'translateY(0px)',
                          display: 'inline-block',
                          width: '186px',
                          fontFamily: 'neirong',
                          textAlign: 'end'
                          }}
                        >{ value ? value.toLocaleString() : "啊？"}</span>
                      </div>
                      <div style={{
                        height: '16px',
                        backgroundColor: '#3690ff1a',
                        borderRadius: 0,
                        width: 'calc(100% - 0px)'
                      }}>
                        <div style={{
                          height: '100%',
                          width: `${(value / max) * 100}%`,
                          backgroundColor: color,
                          borderRadius: 0,
                          background: `linear-gradient(-90deg, ${color}, #0084FF)`,
                          transition: 'width 0.1s ease-in-out',
                        }} />
                      </div>
                    </div>
                  )
                )}
              </div>
            </Card>
          </div>
          <Map />
          <Card title="日志进程ID频率" class="shuzihuanengli">
            <div class="common-subtitle" style="width: 500px;transform: translateX(129%);">日志进程ID频率数据表</div>
            <div class="doudou-row" style="height: 360px;">
              <div
                class="chart-line-szhcgsl doudou-col-12"
                style="height: 100%;"
              />
            </div>
          </Card>
          <div class="aa-right">
            <Card title="当前日志状态" style="height: 28%;">
              <div
                  class="szhnlkapt-title"
                  style="cursor: pointer;"
              >
                日志状态数据表
              </div>
              <div class="netdevice-gaojing">
                <table>
                  <thead>
                  <tr>
                    <th>序号</th>
                    <th>ID</th>
                    <th>时间</th>
                    <th>状态</th>
                  </tr>
                  </thead>
                  <tbody class="scrollable-tbody">
                  {state.tableData.map((item:any, index:any) => {
                    return (
                        <tr>
                          <td title={index.toString()}>{index + 1}</td>
                          <td title={item.id}>{item.id}</td>
                          <td title={item.riqi}>{item.riqi}</td>
                          <td title={item.sta} style={item.sta == '异常' ? 'color: red' : ''}>{item.sta}</td>
                        </tr>
                    );
                  })}
                  </tbody>
                </table>
              </div>
            </Card>
            <Card title="异常事件位置关系" style="height: 35%;">
              <div
                  class="chart-abnormal-event-location-relationship"
                  style="width: 100%;height: 100%;"
              >
              </div>
            </Card>
            <Card title="事件类型比例分析" style="height: 35%;">
              <div
                  class="chart-rizhi-sjlxblsx"
                  style="width: 100%;height: 100%;"
              />
            </Card>
          </div>
        </div>
      </Skeleton>
    )
  }
})
